package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.LoveMusicMapper;
import com.example.onlinemusic.mapper.MusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LXW
 * Date: 2022-07-25
 * Time: 14:26
 */
@RestController
@RequestMapping("/music")
public class MusicController {
    @Value("${music.local.path}")
    private String SAVE_PATH;

    @Autowired
    private MusicMapper musicMapper;

    @Autowired
    private LoveMusicMapper loveMusicMapper;

    /**
     * 上传音乐
     * @param singer
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,
                                                    @RequestParam("filename") MultipartFile file,
                                                    HttpServletRequest request,
                                                    HttpServletResponse response) throws IOException {
        // 检查是否登录 (没有session就不创建)
        HttpSession httpSession = request.getSession(false);
        if (httpSession == null || httpSession.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            System.out.println("没有登录！");
            return new ResponseBodyMessage<>(-1, "没有登录！", false);
        }
        String filenameAndType = file.getOriginalFilename();//xxx.mp3
        System.out.println("filenameAndType: " + filenameAndType);
        String path = SAVE_PATH + filenameAndType;
        File dest = new File(path);
        System.out.println("dest:=>" + dest.getPath());
        if (!dest.exists()) {
            dest.mkdirs();
        }
        try {
            file.transferTo(dest);//上传文件到目标
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "上传文件失败！", false);
        }
        //数据库当中存储的歌曲名称不包含.mp3. 所以，需要进行截取。
        String title = filenameAndType.substring(0, filenameAndType.lastIndexOf("."));
        //SimpleDateFormat来格式化当前的系统时间
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sf.format(new Date());
        //这里会被用到 播放音乐的模块(播放音乐的url)
        String url = "/music/get?path=" + title;
        User user = (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userId = user.getId();
        int ret = musicMapper.insert(title, singer, time, url, userId);
        if (ret == 1) {
            // 前端实现好后需要更改，跳转页面
            response.sendRedirect("/list.html");
            return new ResponseBodyMessage<>(0, "上传成功！", true);
        } else {
            //System.out.println("上传失败！");
            dest.delete();
            return new ResponseBodyMessage<>(-1, "数据库上传失败,删除上传的音乐！", false);
        }
    }

    /**
     * 播放音乐
     * @param path
     * @return
     */
    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path) {
        File file1 = new File(SAVE_PATH + path);
        try {
            byte[] bytes = Files.readAllBytes(file1.toPath());
            if(bytes == null) {
                return ResponseEntity.badRequest().build();
            }else {
                return ResponseEntity.ok(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除单个音乐
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id) {
        // 1.先检查当前id的音乐是否存在
        int iid = Integer.parseInt(id);
        Music music = musicMapper.findByID(iid);
        // 2.如果存在则进行删除
        if(music == null) {
            System.out.println("当前id的音乐不存在");
            return new ResponseBodyMessage<>(-1, "没有你要删除的音乐", false);
        }else {
            // 2.1 删除数据库
            int ret = musicMapper.deleteMusicById(iid);
            if(ret == 1) {
                // 2.2 删除服务器上的数据
                // 同步删除lovemusic表中的数据
                loveMusicMapper.deleteLoveMusicById(iid);
                int index = music.getUrl().lastIndexOf("=");
                String fileName = music.getUrl().substring(index + 1);

                File file = new File(SAVE_PATH + fileName + ".mp3");
                System.out.println("当前的路径： " + file.getPath());
                if(file.delete()) {
                    return new ResponseBodyMessage<>(200, "删除服务器音乐成功", true);
                }else {
                    return new ResponseBodyMessage<>(-1, "删除服务器音乐失败", false);
                }
            }else {
                // 删除数据库失败
                return new ResponseBodyMessage<>(-1, "删除数据库音乐失败", false);
            }
        }
    }

    /**
     * 批量删除音乐
     * @param id
     * @return
     */
    @RequestMapping("/deletesel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]") List<Integer> id) {
        System.out.println("所有ID: " + id);
        int sum = 0;
        for(int i = 0; i < id.size(); i++) {
            int music_id = id.get(i);
            Music music = musicMapper.findByID(music_id);
            if(music == null) {
                System.out.println("没有此id对应的音乐");
                return new ResponseBodyMessage<>(-1, "没有你要删除的音乐", false);
            }
            // 删除数据库中的音乐
            // 同步删除lovemusic表中的数据
            loveMusicMapper.deleteLoveMusicById(music_id);
            int ret = musicMapper.deleteMusicById(music_id);
            if(ret == 1) {
                // 删除服务器中的音乐
                int index = music.getUrl().lastIndexOf("=");
                String fileName = music.getUrl().substring(index + 1);
                File file = new File(SAVE_PATH + fileName + ".mp3");
                if(file.delete()) {
                    sum += ret;
                }else {
                    System.out.println("删除失败");
                    return new ResponseBodyMessage<>(-1, "删除服务器音乐失败", false);
                }
            }else {
                System.out.println("删除失败");
                return new ResponseBodyMessage<>(-1, "删除数据库的音乐失败", false);
            }
        }
        // 检测批量删除是否成功
        if(sum == id.size()) {
            System.out.println("删除成功");
            return  new ResponseBodyMessage<>(200, "批量删除成功", true);
        }else {
            System.out.println("删除失败");
            return new ResponseBodyMessage<>(-1, "批量删除失败", false);
        }
    }

    /**
     * 查询音乐
     * @param musicName
     * @return
     */
    @RequestMapping("/findmusic")
    public ResponseBodyMessage<List<Music>> findMusicByName(@RequestParam(required = false) String musicName) {
        List<Music> musicList = null;
        if(musicName != null) {
            musicList = musicMapper.findMusicByMusicName(musicName);
        }else {
            musicList = musicMapper.findMusic();
        }
        return new ResponseBodyMessage<>(200, "查询到了歌曲信息", musicList);
    }
}
